var PENDING = false;
$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = 'expires=' + d.toGMTString();
    document.cookie = cname + '=' + cvalue + '; ' + expires;
}

function getCookie(cname) {
    var name = cname + '=';
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return '';
}

function frotendrequest(_option) {
    var option = {
        url: null,
        data: null,
        datatype: 'json',
        callback: null
    };
    if (_option)
        $.each(_option, function(index, value) {
            option[index] = value;
        });
    if (option.datatype.toUpperCase() === 'JSON') {
        option.data.ajaxtype = 'json';
    }
    return {
        call: function(_url, _data, _callback) {
            if (PENDING === true)
                return;
            if (_url)
                option.url = _url;
            if (_data)
                option.data = _data;
            if (_callback)
                option.callback = _callback;
            PENDING = true;
            jQuery.ajax({
                type: 'POST',
                //cache:false,
                //timeout:10000,
                data: option.data,
                dataType: option.datatype,
                url: option.url,
                success: function(data_result) {
                    PENDING = false;
                    if (typeof(option.callback) === 'function')
                        option.callback(data_result);
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    PENDING = false;
                    WarningMessage('Sorry. Your request could not be completed.<br/> Please check your input data and try again.');
                }
            });
        }
    };
}

function NoticeMessage(msg) {
    $('#NoticeMessage .dialog-modal-content').html(msg);
    $('#NoticeMessage,.dialog-modal-marker').fadeIn();
}

function WarningMessage(msg) {
    $('#WarningMessage .dialog-modal-content').html(msg);
    $('#WarningMessage,.dialog-modal-marker').fadeIn();
}

function CloseMessage() {
    $('.dialog-modal-dialog,.dialog-modal-marker').fadeOut();
}

function loadalbum() {
    if (PENDING) return;
    if ($('#frmalbumunlock').validationEngine('validate') === false) return false;
    PENDING = true;
    $('.login-album .dialog-modal-footer .dialog-pending').show();
    $('.login-album .dialog-modal-footer p').hide();
    jQuery.ajax({
        type: 'POST',
        //cache:false,
        //timeout:10000,
        data: {
            album_code: $('#album_code').val()
        },
        dataType: 'json',
        url: '/tamchau/home/loadalbum',
        success: function(data_result) {
            PENDING = false;
            setTimeout(function() {
                if (data_result.result > 0) {
                    $('#thu-vien-boxs').html(data_result.album);
                    album_init();
                } else {
                    NoticeMessage(data_result.message);
                }
                $('.login-album .dialog-modal-footer .dialog-pending').hide();
                $('.login-album .dialog-modal-footer p').show();
            }, 1000);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            PENDING = false;
            $('.login-album .dialog-modal-footer .dialog-pending').hide();
            $('.login-album .dialog-modal-footer p').show();
            NoticeMessage('Sorry. Your request could not be completed.<br/> Please check your input data and try again.');
        }
    });
}

function loadSetMenu(code){
    PENDING = true;
    jQuery.ajax({
        type: 'POST',
        //cache:false,
        //timeout:10000,
        data: {
            album_code: code
        },
        dataType: 'json',
        url: '/tamchau/home/getSetMenu',
        success: function(data_result) {
            PENDING = false;
            
            if (data_result.result > 0) {
                $('.setmenu-detail .setmenu-content').html(data_result.setmenu);
                if ($("a.swipebox").length > 0) {
                    $("a.swipebox").swipebox({
                        useCSS: true, // false will force the use of jQuery for animations
                        //hideBarsDelay: 0 // 0 to always show caption and action bar
                    });
                }
            } else {
                NoticeMessage(data_result.message);
            }
            
        },
        error: function(xhr, ajaxOptions, thrownError) {
            PENDING = false;
            NoticeMessage('Sorry. Your request could not be completed.<br/> Please check your input data and try again.');
        }
    });
}

function newcontactus() {
    if (PENDING) return;

    if ($('#frmcontactus').validationEngine('validate') === false) return false;
    var Params = $('#frmcontactus').serializeObject();
    PENDING = true;
    jQuery.ajax({
        type: 'POST',
        //cache:false,
        //timeout:10000,
        data: {
            Params: Params
        },
        dataType: 'json',
        url: '/home/addcontacus',
        success: function(data_result) {
            PENDING = false;
            if (data_result.result > 0) {
                document.frmcontactus.reset();
            }
            NoticeMessage(data_result.message);

        },
        error: function(xhr, ajaxOptions, thrownError) {
            PENDING = false;
            NoticeMessage('Sorry. Your request could not be completed.<br/> Please check your input data and try again.');
        }
    });
}

function centersync2(number) {
    var sync2 = $('#owl-thumb-gallery');
    var sync2visible = sync2.data('owlCarousel').owl.visibleItems;
    var num = number;
    var found = false;
    for (var i in sync2visible) {
        if (num === sync2visible[i]) {
            found = true;
            break;
        }
    }
    if (found === false) {
        if (num > sync2visible[sync2visible.length - 1]) {
            sync2.trigger('owl.goTo', num - sync2visible.length + 2);
        } else {
            if (num - 1 === -1) {
                num = 0;
            }
            sync2.trigger('owl.goTo', num);
        }
    } else if (num === sync2visible[sync2visible.length - 1]) {
        sync2.trigger('owl.goTo', sync2visible[1]);
    } else if (num === sync2visible[0]) {
        sync2.trigger('owl.goTo', num - 1);
    }
}

function album_init() {
    if ($('#gallery').length > 0) {
        //$('#gallery img').parent().nailthumb({replaceAnimation :null});
        var sync1 = $('#gallery');
        var sync2 = $('#owl-thumb-gallery');
        sync1.owlCarousel({
            singleItem: true,
            navigation: false,
            pagination: false,
            lazyLoad: true,
            afterAction: function(el) {
                var current = this.currentItem;
                sync2
                    .find('.owl-item')
                    .removeClass('synced')
                    .eq(current)
                    .addClass('synced');
                if (sync2.data('owlCarousel') !== undefined) {
                    centersync2(current);
                }
            }

        });
        sync2.owlCarousel({
            items: 1,
            itemsCustom: [
                [0, 4],
                [450, 4],
                [640, 4]
            ],
            lazyLoad: true,
            navigation: true,
            navigationText: ['', ''],
            pagination: false,
            afterUpdate: function() {
                //$('.khung_thumb a img').width($('.synced').width() - 12 );
            },
            afterInit: function(el) {
                el.find('.owl-item').eq(0).addClass('synced');
            }
        })
        .on('click', '.owl-item', function(e) {
            e.preventDefault();
            var number = $(this).data('owlItem');
            sync1.trigger('owl.goTo', number);
        });


    }
}

$(document).ready(function() {
    if ($('#background-fullscreen img').length > 0)
        $('#background-fullscreen img').parent().nailthumb({
            replaceAnimation: null
        });
    if ($('#navbar').length > 0) {
        /**/
        $('#navbar').niceScroll('#navbar>div', {
            cursoropacitymax: 0.8,
            cursoropacitymin: 0.4,
            touchbehavior: true,
            cursorborder: '0',
            scrollspeed: 100,
            bouncescroll: false,
            horizrailenabled: false,
            //autohidemode: false,
            cursorcolor: '#FFF900',
            cursorwidth: 4,
            cursorborderradius: 0
        });
        /**/
    }
    if ($('#tiec-cuoi-boxs').length > 0)
        $('#tiec-cuoi-boxs .front').niceScroll('#tiec-cuoi-boxs .front>.wrapper', {
            cursoropacitymax: 0.8,
            cursoropacitymin: 0.4,
            touchbehavior: true,
            cursorborder: '0',
            scrollspeed: 100,
            bouncescroll: false,
            horizrailenabled: false,
            //autohidemode: false,
            cursorcolor: '#27A800',
            cursorwidth: 4,
            cursorborderradius: 0
        });





    if ($('#frmcontactus').length > 0)
        $('#frmcontactus').validationEngine({
            isPopup: true
        });
    if ($('#frmalbumunlock').length > 0)
        $('#frmalbumunlock').validationEngine({
            isPopup: false
        });

    if ($('img.lazy').length > 0)
        $('img.lazy').lazyload();
    try {
        if ($('a.swipebox').length > 0) {
            $('a.swipebox').swipebox({
                useCSS: true
            });
        }
    } catch (e) {}
    $(active_menu).addClass('active');
    $('.go-to-top').click(function() {
        $('body,html').animate({
            scrollTop: 0
        }, 1000);
    });

});

var t = function() {};
try {
    $(window).scroll(function() {
        var st = $(window).scrollTop();
        if (st > 200) {
            $('.go-to-top').fadeIn();
        } else {
            $('.go-to-top').fadeOut();

        }
    }).resize(function() {
        clearTimeout(t);
        t = setTimeout(function() {
            $('#background-fullscreen img').parent().nailthumb({
                replaceAnimation: null
            });
            if ($('#gallery img').length > 0)
                $('#gallery img').parent().nailthumb({
                    replaceAnimation: null
                });
        }, 1000);


    });

} catch (e) {}